import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";


interface ProductSearchState {
  loading: boolean;
  error: string | null;
  SearchList: any;
  pagination:any
}

const initialState: ProductSearchState = {
  loading: true,
  error: null,
  SearchList: null,
  pagination:null
};

//promise
export const searchProduct = createAsyncThunk(
    "productSearch/searchProduct",
    async (paramaters: {
      keywords: string,
      nextPage: number | string,
      pageSize: number | string,
    }, thunkAPI) => {
      let url = `http://123.56.149.216:8080/api/touristRoutes?pageNumber=${paramaters.nextPage}&pageSize=${paramaters.pageSize}`;
      if (paramaters.keywords) {
        url += `&keyword=${paramaters.keywords}`
      }
      const response = await axios.get(
        url
      )
      return {
        data: response.data,
        pagination: JSON.parse(response.headers["x-pagination"])
      }
    }
  )



export const productSearchSlice = createSlice({
  name: "productSearch",
  initialState,
  extraReducers: {
    [searchProduct.pending.type]: (state) => {
      // return {...state,loading:true}
      state.loading = true;
    },
    [searchProduct.fulfilled.type]: (state, action) => {
      state.SearchList = action.payload.data;
      state.pagination= action.payload.pagination;
      state.loading = false;
    },
    [searchProduct.rejected.type]: (
      state,
      action: PayloadAction<string | null>
    ) => {
      state.error = action.payload;
      state.loading = false;
    },
  },
  reducers: {},
});
